#include<stdio.h>
#include <pthread.h>
#include <stdlib.h>

#define NUM_THREADS     50
int count=0,N;

pthread_t threads[NUM_THREADS];


//Thread Function
void *threadFunc(void *threadid)
{

int i,rc;
long t; void *status;

pthread_attr_t attr;
   /* Initialize and set thread detached attribute */
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

   long tid;
   tid = (long)threadid;
   printf("%ld!\n", tid);
	count++;
  if(count <N)
	{
			t=count;

		      //printf("In main: creating thread %ld\n", t);
		      rc = pthread_create(&threads[t], &attr, threadFunc, (void *)t);
		      if (rc){
		         printf("ERROR; return code from pthread_create() is %d\n", rc);
		         exit(-1);
		      }
			//count++;	 



		   /* Free attribute and wait for the other threads */
		   pthread_attr_destroy(&attr);
		      rc = pthread_join(threads[t], &status);
		      if (rc) {
		         printf("ERROR; return code from pthread_join() is %d\n", rc);
		         exit(-1);
		         }

		

	}
	printf("%ld\n", tid);
   pthread_exit(NULL);
}


//Main Function
int main(int argc, char *argv[])
{

int i,rc;
long t=0; void *status;

pthread_attr_t attr;
   /* Initialize and set thread detached attribute */
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);


if(argc==2 && argc < NUM_THREADS){
	
N = atoi(argv[1]);
printf("Number of threads asked: %d\n", N);



      //printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[0], &attr, threadFunc, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }	 



   /* Free attribute and wait for the other threads */
   pthread_attr_destroy(&attr);
      rc = pthread_join(threads[0], &status);
      if (rc) {
         printf("ERROR; return code from pthread_join() is %d\n", rc);
         exit(-1);
         }

printf("Game Over! Now Main is exiting... %d out of %d threads have completed!\n", count, N);
pthread_exit(NULL);

}else
printf("Wrong parameters\n");




}
